package com.pocketpets.model.map;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

import com.google.android.maps.GeoPoint;
import com.google.gson.Gson;
import com.pocketpets.globaldata.ItemListClass;
import com.pocketpets.globaldata.LocationData;
import com.pocketpets.service.ServiceFactory;
import com.pocketpets.service.ServiceType;
import com.pocketpets.service.attraction.IAttractionService;
import com.pocketpets.service.attraction.JsonAttractionService;
import com.pocketpets.task.LoadItemFromDatabaseTask;
import com.pocketpets.ui.map.AttractionLayerTw;
import com.pocketpets.ui.map.AttractionSpot;

public class Attraction extends AsyncTask{
	private static boolean online;
	private static IAttractionService attractionService= (IAttractionService) ServiceFactory.getDefaultInstance().getService(ServiceType.T_ATTRACTION);
	private static SpotDbAdapter mDbHelper;
	private static ProgressDialog dialog;
	static AttractionLayerTw aLayer;
	
	public static String getBrief(String cid)
	{
		return attractionService.getAttractionBriefService(cid);
	}
	
	public static AttractionLayerTw getLocation(Context mContext,AttractionLayerTw attLayer,int zoomLevel,double topLat,double topLon,double bottomLat,double bottomLon)
	{
		online=false;
		if (online)
		{
			return getItemFromService(attLayer,zoomLevel,topLat,topLon,bottomLat,bottomLon);
		}
		else 
		{
			return getItemFromDatabase(mContext,attLayer);
		}
	}
	
	public static AttractionLayerTw getItemFromService(AttractionLayerTw attLayer,int zoomLevel,double topLat,double topLon,double bottomLat,double bottomLon)
	{
		JsonAttractionService jas=new JsonAttractionService();
		//JSONArray jArray=new JSONArray();
		GeoPoint point = new GeoPoint(22336004, 114263971);
		//GeoPoint point = new GeoPoint(JsonAttractionService.getAttraction(MinX, MinY, MaxX, MaxY));
		
		//ArrayList<AttractionSpot> aspot=attractionService.getAttraction(zoomLevel, topLat,bottomLon , 22.361,topLon);
		ArrayList<AttractionSpot> aspot=attractionService.getLocationService(15, 22.254, 114.106, 22.361,114.220);
		AttractionSpot overlayitem = new AttractionSpot(point, "TestSpot1", attractionService.getAttractionBriefService("attr1"),1 );
		attLayer.addOverlay(overlayitem);
		for (AttractionSpot s:aspot)
		{
			attLayer.addOverlay(s);
		}
		return attLayer;
	}
//	http://143.89.191.113/cgi-bin/src/attr_j.php?CTL=101&USERID=&CREDENTIAL=&LAYER=12&MAXX=22.361&MINY=114.106&MINX=22.254&MAXY=114.220
	public static AttractionLayerTw getItemFromDatabase( final Context mContext, AttractionLayerTw attLayer)
	{
		
		mDbHelper = new SpotDbAdapter(mContext);
        mDbHelper.open();
        // Get a cursor to all the locations in the database
        Cursor spotCursor = mDbHelper.fetchAllSpotinfo();
        //startManagingCursor(spotCursor);
        // Move to the first row in the cursor
        spotCursor.moveToFirst();
        do{ // for all the rows in the cursor
        // Get the spot's name, latitude and longitude
        LocationData itemStruct=new LocationData();
        itemStruct.setTitle(spotCursor.getString(spotCursor.getColumnIndexOrThrow(SpotDbAdapter.KEY_SPOT)));
        itemStruct.setLat(spotCursor.getDouble(spotCursor.getColumnIndexOrThrow(SpotDbAdapter.KEY_LATITUDE)));
        itemStruct.setLng(spotCursor.getDouble(spotCursor.getColumnIndexOrThrow(SpotDbAdapter.KEY_LONGITUDE)));
        itemStruct.setPic(spotCursor.getString(spotCursor.getColumnIndexOrThrow(SpotDbAdapter.KEY_PIC)));
        ItemListClass.addToItemList(itemStruct);
//        	String spot =
//        spotCursor.getString(spotCursor.getColumnIndexOrThrow(SpotDbAdapter.KEY_SPOT));
//        double latitude =
//        spotCursor.getDouble(spotCursor.getColumnIndexOrThrow(SpotDbAdapter.KEY_LATITUDE));
//        double longitude =
//        spotCursor.getDouble(spotCursor.getColumnIndexOrThrow(SpotDbAdapter.KEY_LONGITUDE));
//        String coordinates = String.format("Longitude: %1$s\nLatitude: %2$s",longitude, latitude);
//        String pic=spotCursor.getString(spotCursor.getColumnIndexOrThrow(SpotDbAdapter.KEY_PIC));
        // Geopoint refers to the location. Need to specify latitude,
        // longitude in microdegrees
        GeoPoint point = new GeoPoint((int)(itemStruct.getLat()*1e+6),(int)(itemStruct.getLng()*1e+6));
        // Create an overlay item for the spot
        AttractionSpot overlayitem = new AttractionSpot(point,itemStruct.getTitle(),itemStruct.getPic(),0);
        // Add the overlay item into the HelloItemizedOverlay for each spot
        attLayer.addOverlay(overlayitem);
        } while (spotCursor.moveToNext());
     // until you exhaust all the rows. returns false when we reach the end of the cursor
       
        spotCursor.close();
	      
		return attLayer;
	}
	
	
	/*
	public static ArrayList<JSONObject> getAttraction(int zoomLevel,String cid)
	{
		JsonAttractionService jas=new JsonAttractionService();
		//JSONArray jArray=new JSONArray();
		//ArrayList<AttractionSpot> aspot=attractionService.getAttraction(zoomLevel, topLat,bottomLon , 22.361,topLon);
		ArrayList<JSONObject> aAttractionObject=attractionService.getAttractionService(zoomLevel,cid);
//		for (AttractionSpot s:aspot)
//		{
//			attLayer.addOverlay(s);
//		}
		return aAttractionObject;
	}
	*/
	
	public static LocationData[] getAttraction(int zoomLevel,String cid)
	{
		Gson gson=new Gson();
		JsonAttractionService jas=new JsonAttractionService();
		LocationData [] aAttr_Struct =gson.fromJson(attractionService.getGsonAttractionService(zoomLevel,cid), LocationData[].class);
		return aAttr_Struct;
	}
	
	public static Bitmap getPicture(String pic)
	{
		try {
			//url = new URL("http://tripandcity.com/cgi-bin/photoSrc/image.php?CTL=0&CREDENTIAL=&USERID=&PIC_ID=807c3fc1-37cd-4a66-b568-72f5929678ad");
			URL url = new URL("http://tripandcity.com/cgi-bin/photoSrc/image.php?CTL=0&CREDENTIAL=&USERID=&PIC_ID="+pic);

			URLConnection con = url.openConnection();
			InputStream in = con.getInputStream();
			//BufferedImage img = ImageIO.read(in);
			Bitmap bitmap = BitmapFactory.decodeStream(in);
			in.close();
			return bitmap;
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static void saveToFavourite(LocationData locationData)
	{
		//FavouriteList.getAttractionStructure().add(attractionStructure);
	}
	

	@Override
	protected Object doInBackground(Object... arg0) {
		return null;
	}

}
